import { Component, OnInit} from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
import "assets/js/bootstrap-switch.min.js";
import "assets/css/bootstrap-switch.min.css";

declare var $: any;
declare var echarts: any;
declare var Viewer: any;
@Component({
	selector: 'sa-drawings-scheme',
	templateUrl: './drawings-scheme.component.html',
	styleUrls: ['./drawings-scheme.component.css']
})
export class DrawingsSchemeComponent implements OnInit {
    tableData = []; //table数据    侧挂链条
	totalCount: number = 0; //分页总条数   侧挂链条
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	tableParam: any = {
        useTypeL2: '0213',
        number: '',
        componentType: '',
        componentName: '',
        userName: '',//录入人员
        enable: '',
        startTime: '',
        endTime: '',
        searchKey: '',
        type: '',//是否导出  空:否  1:是
	}
	userList: any = [];//用户数据List
	
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
		});
	}
	validatorOptions = {
        excluded:[":disabled"],
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            useTypeL2: {
//              trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请选择车型'
                    }
                }
            },
            componentType: {
//              trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请选择零件类型'
                    }
                }
            },
            componentName:{
                validators: {
                    notEmpty: {
                        message: '请输入零件名称'
                    }
                }
            },
            componentSize:{
                validators: {
                    notEmpty: {
                        message: '请输入零件规格'
                    }
                }
            },
            material:{
                validators: {
                    notEmpty: {
                        message: '请输入材料规格'
                    }
                }
            },
            count:{
                validators: {
                    notEmpty: {
                        message: '请输入数量'
                    }
                }
            },
            eventTime:{
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请选择项目时间'
                    }
                }
            }
        }
    }
	ngOnInit() {
	    this.initSwitch();
		this.initAllUser().then(() => {
			this.selectUserName();
		});
		this.load();
	}
	ngOnDestroy() {
		document.onclick = null;
	}

	// 接收子组件传递过来的数据 
    getSelectTableTime(time) {
        this.tableParam.startTime = time.startTime;
        this.tableParam.endTime = time.endTime;
    } 
	//擦除用户所选值
	delUserName() {
		this.tableParam.userName = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect2').val("");
		$("#select2-userNameSelect2-container").empty();
		$("#select2-userNameSelect2-container").attr("title", "");
		$("#select2-userNameSelect2-container").prepend(str);
	}
	//初始化select2 选项
	selectUserName() {
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				$("#userNameSelect2").select2({
					language: "zh-CN",
					placeholder: "请选择",
					allowClear: true,
					data: this.userList,//为Select添加数据
					templateResult: this.formatRepo
				}).on("select2:select", function (e) {
					var data = e.params.data;
					that.tableParam.userName = data.text;
				});
			})
		})
	}
	//select2 格式回调函数
	formatRepo(state) {
		if (!state.id) { return state.text };
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//拉取
	initAllUser() {
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("user/getUserList.html", null).subscribe(data => {
				if (data.success) {
					var userList = data.data;
					var selectdata = [];
					for (var i = 0; i < userList.length; i++) {
						var obj = {
							id: userList[i].userName,
							text: userList[i].name,
						}
						selectdata[i] = obj;
					}
				}
				that.userList = selectdata;
				resolve();
			})
		})
	}
	//table刷新
	refresh() {
		this.load();
	}
	//表格搜索
	tableSearch() {
		this.curPage = 1;
		this.tableParam.searchKey = common.stringTrim(this.tableParam.searchKey);
		this.load();
	}
    //分页回调
    paginate(e) {
        this.curPage = e.page + 1;
        this.pageSize = e.rows;
        this.load();
    }
    btnClick(type){
        this.tableParam.useTypeL2 = type;
        this.curPage = 1;
        this.load();
    }
	//初始化加载list数据
	load() {
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
			    componentType: this.tableParam.componentType,
			    enable: this.tableParam.enable,
			    useTypeL2: this.tableParam.useTypeL2,
                startTime: this.tableParam.startTime,
                endTime: this.tableParam.endTime,
                createForUser: this.tableParam.userName,//录入人员
                searchKey: this.tableParam.searchKey,
            },
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("drawManage/pageList.html", reqdata).subscribe(result => {
    	    this.tableData = result.exhibitDatas || [];
            this.totalCount = result.recordCount;
		})
	}
	// 导出
//	table_export(){
//	    this.tableParam.reportDate = $('#reportDate').val();
//	    let data = {
//          pageSize: this.pageSize,
//          nowPage: this.curPage,
//          parameters: {
//              componentType: this.tableParam.componentType,
//              enable: this.tableParam.enable,
//              useTypeL2: this.tableParam.useTypeL2,
//              startTime: this.tableParam.startTime,
//              endTime: this.tableParam.endTime,
//              createForUser: this.tableParam.userName,//录入人员
//              searchKey: this.tableParam.searchKey,
//          },
//      }
//	    common.exprotDataFile(data, "gridPager", config.BaseURL+'deviceInstallRecord/vehiclesList.html');
//	}
	// 删除功能
	deleteRow(row){
		this.jsonApiService.confirm_message('删除数据将永久删除，确认要删除?').then(()=>{
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("drawManage/deleteById.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}
	
	/**
	 * 图纸方案添加模块================================================================================================================== 
	 */
	drawingsSchemeForm:any = {
	    id: '',
	    useTypeL2: '0213',
	    componentType: '挂齿版',
	    componentName: '',
	    componentSize: '',
	    material: '',
	    count: '',
	    drawManageDetailEntities:[],
	    fileUrl: '',
	    enable: '1',
	}
	initSwitch() {
        var that = this;
        $('.isStatus').bootstrapSwitch('destroy');  
        $('.isStatus').bootstrapSwitch({    //初始化按钮
            onText: "开启",
            offText: "关闭",
            onColor: "primary",
            offColor: "warning",
            onSwitchChange: function (event, state) {
                that.drawingsSchemeForm[event.target.name] = state? '1': '0';
            }
        });
    }
	// 添加图纸方案
	addDrawingsScheme(modal){
	    if(this.isViewer && $(".viewer-container").length >0){
            this.viewer.destroy();
        }
	    var that = this;
	    this.formType = 'new';
	    modal.show();
	    this.drawingsSchemeForm = {
            id: '',
            useTypeL2: '',
            componentType: '',
            componentName: '',
            componentSize: '',
            material: '',
            count: '',
            drawManageDetailEntities:[],
            fileUrl: '',
            enable: '1',
        }
	    setTimeout(()=>{
            that.initSwitch();
            that.partTypeChange()
        },10)
	    this.imageInfo.imageList = [];
	}
	formType:string = 'new';
    popPartTypeOption = [];
    // 查询零件类型
    partTypeChange(){
		let reqdata = `useTypeL2=${this.drawingsSchemeForm.useTypeL2}`;
		this.jsonApiService.http("drawManage/componentType/componentTypeFind.html", reqdata).subscribe(result => {
            if(!result.data.length){
                this.jsonApiService.message('未添加零件类型!');
            }
            this.popPartTypeOption = result.data || [];
		})
	}
    clickPartType(){
        if(this.popPartTypeOption.length == 0){
            this.jsonApiService.message('请先选择车型!');
        }
    }
	useTypeL2Change(){
	    if(this.drawingsSchemeForm.useTypeL2 && this.drawingsSchemeForm.componentType){
	        this.getDrawingsMatch();
	    }
	}
	getDrawingsMatch(){
	    this.drawingsSchemeForm.drawManageDetailEntities = [];
	    let reqdata = {
	        useTypeL2: this.drawingsSchemeForm.useTypeL2,
	        componentType: this.drawingsSchemeForm.componentType,
	    }
	    this.jsonApiService.http_obj("drawMatch/queryDrawMatch.html", reqdata).subscribe(data => {
            if(data.success){
                let res = data.data.drawDetailEntities;
                if(!res){
                    this.jsonApiService.message('未找到匹配规则,请先添加图纸匹配规则');
                    return
                }
                for(let item of res){
                    if(item.select == 1){
                        let obj = {
                            "index": item.index,
                            "max": '',
                            "min": '',
                            "name": item.name
                        }
                        this.drawingsSchemeForm.drawManageDetailEntities.push(obj);
                    }
                }
            }
        })
	}
	viewRow(row,modal){
	    if(this.isViewer && $(".viewer-container").length >0){
            this.viewer.destroy();
        }
	    this.formType = 'readonly';
	    this.drawingsSchemeForm = JSON.parse(JSON.stringify(row));
	    this.imageInfo.imageList = [];
	    this.imageInfo.imageList.push(this.drawingsSchemeForm.fileUrl);
        modal.show();
	}
	// 编辑
	editRow(row,modal){
	    if(this.isViewer && $(".viewer-container").length >0){
            this.viewer.destroy();
        }
	    this.formType = 'update';
	    modal.show();
	    var that = this;
	    let data = JSON.parse(JSON.stringify(row));
	    for(let key in this.drawingsSchemeForm){
	        this.drawingsSchemeForm[key] = data[key];
	    }
        //获取零件类型
        this.partTypeChange();
	    this.imageInfo.imageList = [];
	    this.imageInfo.imageList.push(this.drawingsSchemeForm.fileUrl);
	    setTimeout(()=>{
            that.initSwitch();
        },10)
	}
	// 关闭编辑
	closeDrawingsSchemeModal(modal){
	    $("#drawingsSchemeForm").data('bootstrapValidator').resetForm();
	    modal.hide()
	}
	// 编辑提交
	drawingsSchemeSubmit(modal){
	    $('#drawingsSchemeForm').bootstrapValidator('validate'); //开启验证
        let isValid = $('#drawingsSchemeForm').data('bootstrapValidator').isValid();  //验证是否通过
        if(!isValid){
            return
        }
	    let reqdata = {
	        id: this.drawingsSchemeForm.id,
            useTypeL2: this.drawingsSchemeForm.useTypeL2,
            componentType: this.drawingsSchemeForm.componentType,
            componentName: this.drawingsSchemeForm.componentName,
            componentSize: this.drawingsSchemeForm.componentSize,
            material: this.drawingsSchemeForm.material,
            count: this.drawingsSchemeForm.count,
            enable: this.drawingsSchemeForm.enable,
            drawManageDetailEntities: JSON.stringify(this.drawingsSchemeForm.drawManageDetailEntities),
            fileUrl: this.drawingsSchemeForm.fileUrl,
	        
	    }
	    let hasVal:boolean = true;
	    for(let item of this.drawingsSchemeForm.drawManageDetailEntities){
	        if(!item.min || !item.max){
	            hasVal = false;
	            break;
	        }
	    }
	    if(!hasVal){
	        this.jsonApiService.message('请输入匹配条件');
            return;
	    }
	    if(!this.drawingsSchemeForm.fileUrl){
            this.jsonApiService.message('请上传零件图片');
            return;
        }
	    // 启用,禁用
	    this.jsonApiService.http_obj("drawManage/enableMatch.html", {id: this.drawingsSchemeForm.id,enable: this.drawingsSchemeForm.enable,}).subscribe(data => {
            if(data.success){
                // 表单提交
                this.jsonApiService.http_obj("drawManage/addDrawManage.html", reqdata).subscribe(data => {
                    this.jsonApiService.message(data.message);
                    if(data.success){
                        this.load();
                        modal.hide();
                    }
                })
            }else{
                this.jsonApiService.message(data.message);
            }
        })
	}
	// 图片查看
	imageInfo : any = {
        imageList: [],
        describe: '零件图纸'
    }
    activeImg:any = {
        title:'',
        url:''
    }
    fileList: File = null;
    //上传多张
    multifileChange(files: FileList){
        if(this.isViewer && $(".viewer-container").length >0){
            this.viewer.destroy();
        }
        let multfileList = files;
        var reqdata = new FormData();
        reqdata.append('describe',this.imageInfo.describe);
        reqdata.append('businessType', '3');
        reqdata.append('type', '2'); //type 1获取相对路径  2获取绝对路径
        for(var i = 0; i < multfileList.length; i++){
            this.fileList = multfileList[i];
            const isJPG = this.fileList.type === 'image/jpeg'|| this.fileList.type === 'image/jpg'|| this.fileList.type === 'image/png';
            if (!isJPG) {
            this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!');
            return;
            }
            reqdata.append('files',multfileList[i]);
        }
        this.jsonApiService.form_http("fileUpload/upload.html",reqdata).subscribe(data=> {
            if(data.success){
                for(var i = 0; i < data.data.length; i++) {
                    this.imageInfo.imageList.push(data.data[i]);
                }
                this.drawingsSchemeForm.fileUrl = this.imageInfo.imageList.join(',');
            }
        })
        for(let k = 0; k < $(".up").length; k++) {
            $(".up")[k].value = null;
        }
    }
    
    //删除图片
    deleteImg(index,i){
        if(index == 1){
            this.imageInfo.imageList.splice(i,1);
        }
        if(this.isViewer && $(".viewer-container").length >0){
            this.viewer.destroy();
        }
    }
    imgView(imageUrl,name,modal){
        this.activeImg.title = name;
        this.activeImg.url = imageUrl;
        modal.show();
    }
    // 图片关闭
    imgClose(modal){
        modal.hide();
    }
    //图片放大
    isViewer:Boolean = false;
    viewer:any;
    bigimg(ele){
        if(this.isViewer && $(".viewer-container").length >0){
            this.viewer.destroy();
            System.import('assets/js/viewer/viewer.js').then(
                ()=>{System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
                    ()=>{System.import('assets/js/viewer/viewer.css').then(()=>{
                        this.showImg(ele);
                    })
                })
            })
        }else{
            this.showImg(ele);
        }
        
    }
    showImg(ele){
        var that = this;
        var imgList = $("."+ele)[0];
        this.viewer = new Viewer(imgList, {
            url: 'src',
            title: function (image) {
                return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')' ; 
            },
        });
        this.isViewer = true;
    }

}